#!/usr/bin/env python2

import errno
import os
import sys
import socket
import time
import subprocess
import fcntl
import types
import errno
import getopt
import random

from config import Config
from utils import Exp, _dmsg, _dwarn
from metadata_balance_with_diskmap import get_new_locs

class MoveMetadata:
    def __init__(self, storage, config):
        self.storage = storage
        self.objectbydict = {}
        self.config = config

    def movebylocation(self, chunk, lst):
        locs = self.storage.location(chunk, 3)
        repnum = int(self.storage.stat(chunk)['repnum'])
        if not len(locs) == repnum:
            _dwarn("chunk replica is falt, exit. locs: %s, repnum: %d" % (str(locs), repnum))
            return

        try:
            new_locs = get_new_locs(lst, locs, locs[0])
        except Exp, e:
            if e.errno == errno.EINVAL:
                _dwarn("exit. chunk: %s, error: %s" % (chunk, str(e)))
                return
            else:
                raise Exp(e.errno, str(e))

        if sorted(locs) == sorted(new_locs):
            _dmsg("chunk %s need not move" % (chunk))
            return

        self.storage.move_chunk(chunk, new_locs, True)
